// 引入express
const express = require("express")
// 引入路径处理模块
let path = require('path');
// 导入 cors 中间件
const cors = require('cors')
//引入express-jwt用来解决token的验证问题,express-jwt和jwt都要引入(jwt的加密解密方法在util里面),两者解决的问题不同（jwt用来加密，express-jwt用来验证）。
const { expressjwt } = require("express-jwt")
//引入处理解析中间体模块
let bodyParser = require('body-parser');

const util = require('./utils/index')
const userRouter = require('./routes/user')
const articleRouter = require('./routes/article')
const imageRouter = require('./routes/image')
const compression = require('compression')
const app = express()
// 监听6001端口
app.listen(6001, () => {
    console.log("open '127.0.0.1:6001'")
})
//gzip
app.use(compression())
// 将 cors 注册为全局中间件
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
//解析application/json
app.use(bodyParser.json({ limit: '10mb' }));
//解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({limit:'50mb',extended: true }))


//使用expressJWT对路由进行token验证

let secretOrPrivateKey = "mykey"  //私钥 校验token时要使用

//'/api/image/upload', 
app.use(['/api/user/changePassword', '/api/user/changeAvatar',
    '/api/article/addComment', '/api/user/checkLogin', 
    '/api/article/deleteArticle', '/api/article/saveArticle',
    '/api/user/getUserInfo'], 
    expressjwt({
        secret: secretOrPrivateKey,
        algorithms: ['HS256']
    }))

// .unless({
//     path: ['/api/user/login','/api/user/register', /^\/article\/.*/,'/api/user/getInfo', '/ueditor/ue']  //这里可以设置保护路由，login就不用进行token验证
// }));

app.use('/api/user', userRouter)
app.use('/api/article', articleRouter)
app.use('/api/image', imageRouter)
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'dist')));

//token拦截器，当token失效时发出注销账号指令
app.use(function (err, req, res, next) {
    console.log(err.name);
    originalUrl = req.originalUrl;
    if (err.name === 'UnauthorizedError') {
        res.send({
            code: 401,
            message: "身份未认证或已过期，请重新登录"
        })
        next()
        return
    } else {
        console.log(err)
        res.send({
            code: 404,
            message: "未知错误:" + err.name
        })
        next()
        return
    }
});